package com.shujia.spark.streaming

import org.apache.spark.SparkContext
import org.apache.spark.sql.SparkSession
import org.apache.spark.streaming.dstream.{DStream, ReceiverInputDStream}
import org.apache.spark.streaming.{Durations, StreamingContext}

object Demo3Window {
  def main(args: Array[String]): Unit = {
    val spark: SparkSession = SparkSession
      .builder()
      .appName("window")
      .master("local[2]")
      .getOrCreate()

    val sc: SparkContext = spark.sparkContext

    val ssc = new StreamingContext(sparkContext = sc, batchDuration = Durations.seconds(5))

    val linesDS: ReceiverInputDStream[String] = ssc.socketTextStream("master", 8888)

    /**
     * 滑动窗口统计
     * 每隔5秒统计最近15秒单词的数量
     */
    val countDS: DStream[(String, Int)] = linesDS
      .flatMap(_.split(","))
      .map((_, 1))
      //划分窗口
      .window(Durations.seconds(15), Durations.seconds(5))
      .reduceByKey(_ + _)

    //foreachRDD方法也是每隔5秒运行一次
    countDS.foreachRDD(rdd => {
      //对一个窗口内的数据进行排序取前几
      val top2: Array[(String, Int)] = rdd.sortBy(-_._2).take(2)
      top2.foreach(println)
    })

    ssc.start()
    ssc.awaitTermination()
  }
}
